<?php

namespace App\Repository\UpThree;

use App\Api\Transfer;
use App\Jobs\BigData;
use App\Repository\BaseRepository;
use App\Repository\GetWay\WayRepository;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * 1:小程序商品的设置
 * 2:H5流 直接提交到第三方
 */
class VerificOrderRepository extends BaseRepository
{
    private $model = null;
    private $log;

    public function __construct()
    {
        // 记录的是 第三方成功了 但是本地失败了
        $this->log = new Logger('shop73');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/shop73.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    // 抖音小程序 判断直接提交还是需要支付
    public function douYinIsPay($data = array())
    {
        // var_dump(time());
        if (empty($data['goods_id']) && (empty($data['goods_code']) || empty($data['shop_id']))) {
            return $this->returnMsg(10001, '商品信息不能为空');
        }
        if (empty($data['name'])) {
            return $this->returnMsg(1, '用户名不能为空');
        }
        $name = strip_tags(trim($data['name']));
        $len = mb_strlen($name);
        if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·?]?[\x{4e00}-\x{9fa5}]+$/u', $name, $matchers)) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }
        if ($len < 2 || $len > 10) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }

        //判断手机号
        if (empty($data['contact'])) {
            return $this->returnMsg(10007, '请输入您的手机号码');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $data['contact'])) {
            return $this->returnMsg(10007, '手机号错误，请重新查看');
        }
        if (empty($data['province'])) {
            return $this->returnMsg(10010, '缺少省份');
        }
        if (empty($data['city'])) {
            return $this->returnMsg(10011, '缺少市');
        }
        // if (!$request->has('area')) {
        //     return $this->returnMsg(10012, '缺少区');
        // }

        // $province = strip_tags(trim($data['province']));
        // $city = strip_tags(trim($data['city']));


        if (empty($data['address'])) {
            return $this->returnMsg(10013, '详细地址不能为空');
        }
        $lens = mb_strlen($data['address']);
        if (getStrLen($data['address']) < 2 || $lens > 50) {
            return $this->returnMsg(10006, '详细地址内容不小于2个汉字，请重新输入');
        }
        // 提交过来的字符串处理
        if (!empty($data['identity'])) {
            $data['identity'] = strtoupper(trim($data['identity'], ' '));
        }
        if (!empty($data['identity'])) {
            if (strlen($data['identity']) != 18) {
                return $this->returnMsg(10006, '请输入正确的身份证号');
            }
        }
        $data['address'] = (trim($data['address'], ' '));
        $data['contact'] = (trim($data['contact'], ' '));
        $data['name'] = (trim($data['name'], ' '));
        $params['address'] = $data['address'];
        // 身份信息的验证
        // if (empty($data['identity'])) {
        //     return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        // }
        $idcard = !empty($data['identity']) ? $data['identity'] : '';
        //if (empty($data['identity'])) {
        //     return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        // }
        // if (!is_idcard($idcard)) {
        //     return $this->returnMsg(10007, '身份证号码不正确，请检查');
        // }

        $goods_codeCache = '';
        if (!empty($data['goods_code'])) {
            $goods_codeCache = $data['goods_code'];
        }
        $shop_idCache = '';
        if (!empty($data['shop_id'])) {
            $shop_idCache = $data['shop_id'];
        }
        $goods_idCache = '';
        if (!empty($data['goods_id'])) {
            $goods_idCache = $data['goods_id'];
        }
        $this->orderKeys = $idcard . '_' . $data['contact'] . '_' . $goods_idCache . '_' . $goods_codeCache . '_' . $shop_idCache;
        // 使用缓存防止重复提交 或 重复记录数据
        // $resCache = Cache::get($idcard . '_' . $data['contact']);
        $resCache = Cache::get($this->orderKeys);
        // $oneAdress = Cache::get($idcard . '_' . $data['contact'] . '_address');
        // $oneAdress = Cache::get($this->orderKeys . '_address');
        if (!empty($resCache) && ($resCache == $data['address'])) {
            if ($resCache == $data['address']) {
                return $this->returnMsg(101, '请稍后提交');
            }
            // return  $this->returnMsg(102, $resCache);
        }
        // 防止重复提交

        $getRepeat = Cache::get($this->orderKeys . '_repeat');
        if (!empty($getRepeat) && $getRepeat == 1) {
            return $this->returnMsg(102, '提交中,请稍后重新提交');
        }
        Cache::put($this->orderKeys . '_repeat', 1, Carbon::now()->addMinutes($this->orderKeysTime));
        $isTrueSuccess = Cache::get($this->orderKeys . '_success');
        // var_dump($this->orderKeys . '_success', 1111111111);
        // var_dump($isTrueSuccess, 222222222);
        if (!empty($isTrueSuccess)) {
            return $this->returnMsg(103, '您已提交成功');
        }
        $errorNums = Cache::get($this->orderKeys . '_error');
        // 提交10次错误信息后 直接提示失败
        if ($errorNums >= 10) {
            return $this->returnMsg(105, '请稍后提交');
        }
        if (empty($errorNums)) {
            $errorNums = 0;
        }
        $errorNums++;
        Cache::put($this->orderKeys, $data['address'], Carbon::now()->addMinutes($this->orderKeysTime));
        // 订单号的处理
        $data['orderno'] = !empty($data['dist_orderno']) ? ('HK_' . $data['dist_orderno']) : creatOrderNums('HK_');
        // if (!empty($data['dist_orderno'])) {
        // }
        // 判断订单号是否存在
        $whereIsOrderNo = [
            'ordersno' => $data['orderno'],
        ];
        $isOrder = $this->orderModel->getOne($whereIsOrderNo);
        if (!empty($isOrder)) {
            return $this->returnMsg(1002, '您的订单已存在,请前去更改');
        }
        // 参数验证完了
        $msg = '未查询到下单';
        $flag = true;
        //商品验证
        $whereGoods = [
            'status' => 0,
        ];
        if (!empty($data['goods_id'])) {
            $whereGoods['id'] = $data['goods_id'];
        }
        if (!empty($data['goods_code']) && !empty($data['shop_id'])) {
            $whereGoods['goods_code'] = $data['goods_code'];
            $whereGoods['shop_id'] = $data['shop_id'];
        }
        // var_dump($whereGoods);
        $isValid = true;
        $resGoods = $this->goodsModel->getOne($whereGoods, ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'sup_shop_name', 'sup_shop_id', 'sup_goods_id', 'sup_goods_name', 'shop_id_str', 'shop_name_str', 'shop_id', 'shop_name', 'goods_price', 'goods_point', 'main_pic', 'is_trun']);
        $resGoods = json_decode(json_encode($resGoods), true);
        if (!$resGoods) {
            $flag = false;
            $msg = '未查询到商品信息';
            return $this->returnMsg(100, '未查询到商品信息');
        }
        if (empty($data['shop_id'])) {
            $data['shop_id'] = $resGoods['shop_id'];
        }
        $insertData = [];
        if ($flag) {
            // 添加还是修改 为了存储信息
            $insertData = [
                'orderno' => $data['orderno'],
                'dist_orderno' => !empty($data['dist_orderno']) ? $data['dist_orderno'] : '',
                'dist_id' => !empty($data['dist_id']) ? $data['dist_id'] : 0,
                'dist_name' => !empty($data['dist_name']) ? $data['dist_name'] : '',
                'contact_phone' => !empty($data['contact_phone']) ? $data['contact_phone'] : $data['contact'],
                'contact_name' => !empty($data['contact_name']) ? $data['contact_name'] : $data['name'],
                'pay_name' => $data['name'],
                'pay_phone' => $data['contact'],
                'pay_identity' => $idcard,
                'iccid' => !empty($data['number']) ? $data['number'] : '',
                'province' => !empty($data['numberProvince']) ? $data['numberProvince'] : '',
                'city' => !empty($data['numberCity']) ? $data['numberCity'] : '',
                'post_province' => !empty($data['province']) ? $data['province'] : '',
                'post_city' => !empty($data['city']) ? $data['city'] : '',
                'post_area' => !empty($data['area']) ? $data['area'] : '',
                'post_address' => !empty($data['address']) ? $data['address'] : '',
                'author_id' => !empty($data['author_id']) ? $data['author_id'] : '',
                'author_name' => !empty($data['author_name']) ? $data['author_name'] : '',
                'card_num' => !empty($data['card_num']) ? $data['card_num'] : '',
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'status' => 0,
                'shop_id' => $data['shop_id'],
                'shop_str' => $resGoods['shop_str'],
                'goods_id' => $resGoods['id'],
                'goods_name' => $resGoods['name'],
                'goods_code' => $resGoods['goods_code'],
                'product_id' => $resGoods['product_id'],
                'product_name' => $resGoods['product_name'],
                'product_code' => $resGoods['product_code'],
                'sup_goods_name' => $resGoods['sup_goods_name'],
                'shop_id_str' => $resGoods['shop_id_str'],
                'shop_name_str' => $resGoods['shop_name_str'],
                'sup_goods_id' => $resGoods['sup_goods_id'],
                'sup_goods_id_str' => $resGoods['sup_goods_id_str'],
                'sup_shop_id' => $resGoods['sup_shop_id'],
                'sup_shop_name' => $resGoods['sup_shop_name'],
                'source' => !empty($data['source']) ? $data['source'] : 0,
                'shop_name' => !empty($resGoods['shop_name']) ? $resGoods['shop_name'] : 0,
                'sell_name' => !empty($data['sell_name']) ? $data['sell_name'] : '',
                'is_trun' => !empty($resGoods['is_trun']) ? $resGoods['is_trun'] : 0,
                'pay_money' => !empty($resGoods['goods_price']) ? $resGoods['goods_price'] : '',
            ];
        }
        // 产品验证开始
        $productId = !empty($resGoods['product_id']) ? $resGoods['product_id'] : 0;
        // var_dump($productId, 222222222);

        if (empty($resGoods['product_id'])) {
            if (empty($resGoods['sup_goods_id_str'])) {
                $isValid = false;
                $msgs = '商品出错,请联系管理员';
                // return $this->returnMsg(16, '商品出错,请联系管理员');
            }
            if ($isValid) {
                $productArr = explode('.', $resGoods['sup_goods_id_str']);
                if (empty($productArr[1])) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(17, '该产品无法下单,请联系商家');
                }
            }

            if ($isValid) {
                $disGoods = $this->goodsModel->getOne(['id' => $productArr[1]], ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'status']);
                $disGoods = json_decode(json_encode($disGoods), true);
                if (empty($disGoods['product_id'])) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(18, '请联系供应商,未查询到产品信息');
                }
                if (!empty($disGoods['status']) && $disGoods['status'] == 1) {
                    $isValid = false;
                    $msgs = '该产品无法下单,请联系商家';
                    // return $this->returnMsg(19, '该产品已下架,请联系运营商');
                }
                if ($isValid) {
                    $productId = $disGoods['product_id'];
                    $insertData['product_id'] = $disGoods['product_id'];
                    $insertData['product_name'] = $disGoods['product_name'];
                    $insertData['product_code'] = $disGoods['product_code'];
                }
            }
        }

        if ($flag) {
            $resProduct = $this->validProduct($productId, $data);
            // var_dump($resProduct);
            $isProduct = true;
            if (empty($resProduct['code']) || $resProduct['code'] != 200) {
                // $flag = false;
                $isValid = false;
                $isProduct = false;
                $msgs = $msg = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
                // $insertData['status'] = 50;
                // $insertData['three_msg'] = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
            }
            // 多次开卡问题  同一张卡多次提交
            if (!empty($resProduct['code']) && $resProduct['code'] == 10000) {
                $flag = false;
                $isProduct = false;
                $msg = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
            }
            if (!$isProduct) {
                // var_dump($msg, 11111111);
                Cache::put($this->orderKeys . '_repeat', 2, Carbon::now()->addMinutes($this->orderKeysTime));
                // 防止用户长时间提交
                Cache::put($this->orderKeys . '_error', $errorNums, Carbon::now()->addDay(1));
                return $this->returnMsg(100, $msg);
            }
            // $insertData['sup_orderno'] = !empty($resProduct['data']['order_id']) ? $resProduct['data']['order_id'] : ''; //渠道单号
            // $insertData['sup_id'] = !empty($resProduct['data']['channel_id']) ? $resProduct['data']['channel_id'] : ''; //渠道id
            // $insertData['sup_name'] = !empty($resProduct['data']['channel_name']) ? $resProduct['data']['channel_name'] : ''; //渠道名称
            // $insertData['three_msg'] = !empty($resProduct['data']['msg']) ? $resProduct['data']['msg'] : '';
            // $insertData['channel_error_josn'] = !empty($resProduct['data']['error']) ? $resProduct['data']['error'] : '';
        }
        if (!$isValid) {
            $insertData['status'] = 50;
            $insertData['three_msg'] = !empty($msgs) ? $msgs : '产品效验未过';
        }
        if (!$flag) {
            $flag = true;
            $insertData['status'] = 50;
            $insertData['three_msg'] = !empty($msg) ? $msg : '效验未过';
        }
        // 下单流程
        if (true) {
            // $resOrder = $this->orderModel->add($insertData);
            $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . jsonEncodeMsg($resOrder));
            if (empty($resOrder['code']) || $resOrder['code'] != 200) {
                //第三方提交成功了 但是存储数据库的时候 失败了 记录日志文件方便查看
                $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . jsonEncodeMsg($resOrder));
            }
        }
        Cache::put($this->orderKeys . '_repeat', 2, Carbon::now()->addMinutes($this->orderKeysTime));
        // var_dump(time());
        if ($flag) {
            // 添加到队列中
            Cache::put($this->orderKeys . '_success', '您已下过单,请更新信息在下单', Carbon::now()->addMinutes(60));
            return $this->returnMsg(200, '下单成功', [
                'order' => $insertData['dist_orderno'],
                'order_num' => $insertData['orderno'],
                'money' => !empty($resGoods['goods_price']) ? $resGoods['goods_price'] * 100 : 0,
                'goods_name' => !empty($resGoods['name']) ? $resGoods['name'] : '',
                'goods_point' => !empty($resGoods['goods_point']) ? $resGoods['goods_point'] : '',
                'goods_id' => !empty($resGoods['id']) ? $resGoods['id'] : '',
                'goods_url' => !empty($resGoods['main_pic']) ? $resGoods['main_pic'] : '',
            ]);
        }
        // 防止用户长时间提交
        Cache::put($this->orderKeys . '_error', $errorNums, Carbon::now()->addDay(1));
        return $this->returnMsg(100, $msg);
    }

    // 订单状态本地修正
    public function getOrderStatusEdit($data)
    {
        if (empty($page)) {
            $page = 1;
        }
        if (!empty($data['orderno'])) {
            $page = $data['orderno'];
        }
        // $page = 1;
        $nums = 10;
        $skip = ($page - 1) * $nums;
        $res = DB::table('check_orders')->skip($skip)->take($nums)->get();
        if ($res && !empty($res)) {
            foreach ($res as $key => $v) {
                $v = json_decode(json_encode($v), true);
                if (empty($v['ordersno']) || empty($v['jsons'])) {
                    continue;
                }
                $vs = $v['jsons'];
                if (is_string($v['jsons'])) {
                    $vs = json_decode($v['jsons'], true);
                }
                $whereTrue = [
                    'ordersno' => $v['ordersno'],
                ];
                $orderTrue = DB::table('orders')->where($whereTrue)->first();
                $this->log->info('查询条件1' . json_encode($whereTrue) . '查询出来的结果:' . json_encode($orderTrue) . '获取到的结果:' . json_encode($vs));
                if (!$orderTrue || $orderTrue->status >= $vs['status']) {
                    continue;
                }
                $update = [
                    'status' => $vs['status'],
                    'status_desc' => $this->getOrderStatusDesc($vs['status']),
                    'express_company' => $vs['express_company'],
                    'express_number' => $vs['express_number'],
                ];
                $this->log->info('查询条件2:' . json_encode($whereTrue) . '修改参数' . json_encode($update));
                $isTrue = DB::table('orders')->where($whereTrue)->update($update);
                $this->log->info('查询提交3' . json_encode($whereTrue) . '修改结果' . $isTrue);
            }
        }
        if (count($res) < $nums) {
            return '运行结束';
        }
        $page++;
        dispatch(new BigData($page, 'getOrderStatusEdit', 5))->onQueue('TaskBigDataDispose');
        return 'page:' . $page;
    }

    public function orderStatus()
    {
        return [
            0 => '提交中',
            1 => '提交上游',
            // 2 => '拒收单',
            3 => '需上传证件照',
            10 => '审核中',

            11 => '待发货',
            20 => '已发货',
            30 => '已签收',
            40 => '已激活',
            50 => '异常单',
            51 => '取消单',
            60 => '失败单'
        ];
    }

    public function getOrderStatusDesc($key)
    {
        $allStatus = $this->orderStatus();
        return !empty($allStatus[$key]) ? $allStatus[$key] : '未知状态';
    }

    // 订单状态更新修正
    public function getOrderStatusEdit_back($data)
    {
        $where = [
            'shop_id' => 73,
            'status' => 10,
        ];
        if (empty($page)) {
            $page = 1;
        }
        if (!empty($data['orderno'])) {
            $page = $data['orderno'];
        }
        // $page = 1;
        $nums = 5;
        $skip = ($page - 1) * $nums;
        $res = DB::table('orders')->where($where)->skip($skip)->take($nums)->orderBy('id', 'desc')->orderBy('sup_id', 'desc')->get();
        if ($res && !empty($res)) {
            foreach ($res as $key => $v) {
                $v = json_decode(json_encode($v), true);
                if (empty($v['sup_id'])) {
                    $this->log->info('该订单上游信息为空:' . $v['ordersno']);
                    continue;
                }
                $resOrderWay = $this->getOrderWay($v);
                $this->log->info('返回的参数:' . json_encode($resOrderWay));
                $datas = !empty($resOrderWay['data'][0]) ? $resOrderWay['data'][0] : [];
                // 去查询后处理的订单
                if (!empty($datas)) {
                    $insertData = [
                        'ordersno' => $v['ordersno'],
                        'jsons' => json_encode($datas)
                    ];
                    DB::table('check_orders')->insert($insertData);
                }

                // $update = [
                //   'status' => '',
                //   'express_company' => '',
                //   'express_number' => '',
                // ];
            }
        }
        if (count($res) < 5) {
            return '运行结束';
        }
        $page++;
        dispatch(new BigData($page, 'getOrderStatusEdit', 5))->onQueue('TaskBigDataDispose');
        return 'page:' . $page;
    }

    public function getOrderWay($order)
    {
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $order['sup_id']]);
        if (!$resChannelModel) {
            return [];
        }
        if ($resChannelModel) {
            $resChannelModel = json_decode(json_encode($resChannelModel), true);
        }
        $order['model'] = $order['sup_id'];
        $data = array_merge($order, $resChannelModel);
        $model = new Transfer();
        return $model->queryOneOrder($data);
    }

    public function orderSubmitThree($method, $data)
    {
        $model = new Transfer();
        return $model->$method($data);
    }

    public function getWay($data)
    {
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $data['sup_id']]);
        if (!$resChannelModel) {
            return $this->returnMsg(102, '通道不存在');
        }
        $data['path'] = $resChannelModel->path;
        $data['url'] = $resChannelModel->url;
        $data['parame'] = $resChannelModel->parame;
        return $data;
    }
}
